<template>
  <view class="content">
    <uni-popup ref="popup" type="bottom">
      <view class="settings-list">
        <view class="setting-box" @click="openAlertDialog"> 设备导出 </view>
        <view class="setting-box" @click="openInputDialog"> 设备导入 </view>
        <view class="setting-box" @click="goToSecurity"> 安全配置 </view>
      </view>
    </uni-popup>
    <topNotification ref="topNotificationRef"></topNotification>
    <!-- 弹窗提示 -->
    <uni-popup ref="alertDialogRef" type="dialog">
      <uni-popup-dialog type="info" cancelText="关闭" confirmText="复制" title="提示" content="点击【复制】立刻导出当前所有配置至剪切板，在其他设备应用上点击导入配置，输入后点击确定即可。" @confirm="dialogConfirm"></uni-popup-dialog>
    </uni-popup>
    <!-- 配置输入 -->
    <uni-popup ref="inputDialog" type="dialog">
      <uni-popup-dialog ref="inputClose" mode="input" title="输入配置" placeholder="输入设备配置，不要输入自定义指令！！！" @confirm="dialogInputConfirm"></uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script setup name="Settings">
import { ref } from "vue";
import useComputerStore from "@/store/modules/computer.js";
import _ from "lodash";
import { areArraysEqual } from "@/utils/tools.js";
import { isAuthPass } from "@/utils/authentication.js";

const computerStore = useComputerStore();

// 设置栏弹窗实例
const popup = ref();

// 打开设置
const open = () => {
  popup.value.open("left");
};

// 关闭设置
const close = () => {
  popup.value.close();
};

// 导入配置弹窗实例
const inputDialog = ref();

// 弹窗提示实例
const alertDialogRef = ref();

// 导出配置信息
const dialogConfirm = () => {
  if (isAuthPass()) return;
  let formatComputerList = _.cloneDeep(computerStore.computerList);
  formatComputerList.map((item) => delete item.status);
  uni.setClipboardData({
    data: JSON.stringify(formatComputerList),
    success: () => {
      topNotificationRef.value.sendPopupTip({
        type: "success",
        message: "导出成功，已复制至粘贴板！",
      });
    },
    fail: () => {
      topNotificationRef.value.sendPopupTip({
        type: "error",
        message: "导出失败，请检查应用粘贴权限是否给予",
      });
    },
  });
};

//打开输出弹窗
const openAlertDialog = () => {
  close();
  alertDialogRef.value.open();
};

//打开输入弹窗
const openInputDialog = () => {
  close();
  inputDialog.value.open();
};

//校验配置格式是否正确
const validateArray = (computer_list) => {
  // // 判断外层是不是对象
  // if (Object.prototype.toString.call(data) !== "[object Object]") {
  //   return false;
  // }

  // // 判断对象内参数是否齐全
  // if (areArraysEqual(Object.keys(data), ["batch_command", "computer_list"])) {
  //   if (!Array.isArray(data.batch_command) || !Array.isArray(data.computer_list)) {
  //     return false;
  //   }
  // } else {
  //   return false;
  // }

  // let batch_command = data.batch_command;
  // let computer_list = data.computer_list;

  // 判断批量自定义命令参数
  // let batch_command_valid = Array.isArray(batch_command) && batch_command.every((item) => Object.prototype.toString.call(item) === "[object Object]" && areArraysEqual(Object.keys(item), ["name", "command", "permission"]));
  // 判断设配参数
  let computer_list_valid = true;
  if (!Array.isArray(computer_list)) computer_list_valid = false;
  for (let i = 0; i < computer_list.length; i++) {
    const item = computer_list[i];

    if (Object.prototype.toString.call(item) !== "[object Object]" || !areArraysEqual(Object.keys(item), ["name", "ip", "port", "key", "custom_command"]) || !Array.isArray(item.custom_command)) {
      computer_list_valid = false;
      break;
    }

    let custom_command_valid = true;
    for (let ii = 0; ii < item.custom_command.length; ii++) {
      const element = item.custom_command[ii];
      if (Object.prototype.toString.call(element) !== "[object Object]" && areArraysEqual(Object.keys(element), ["script_id", "script_type", "name", "content", "permission"])) {
        custom_command_valid = false;
        break;
      }
    }

    if (!custom_command_valid) {
      computer_list_valid = false;
      break;
    }
  }
  // return batch_command_valid && computer_list_valid;
  return computer_list_valid;
};

// 顶部提示横幅实例
const topNotificationRef = ref();

// 输入弹窗回调事件
const dialogInputConfirm = (val) => {
  if (isAuthPass()) return;
  let formatValue = null;
  try {
    formatValue = JSON.parse(val.trim());
  } catch (err) {
    topNotificationRef.value.sendPopupTip({
      type: "error",
      message: "配置格式不正确",
    });
  }

  if (validateArray(formatValue)) {
    formatValue.map((item) => {
      item.status = "未知";
    });
    const mergedArray = _.uniqWith([..._.cloneDeep(computerStore.computerList), ...formatValue], (a, b) => a.ip === b.ip && a.port === b.port);
    computerStore.updateComputerList(mergedArray);
    topNotificationRef.value.sendPopupTip({
      type: "success",
      message: "配置成功",
    });
  } else {
    topNotificationRef.value.sendPopupTip({
      type: "error",
      message: "配置格式不正确",
    });
  }
};

// 跳转安全配置
const goToSecurity = () => {
  uni.navigateTo({
    url: "/pages/security/index",
  });
};

defineExpose({ open, close });
</script>

<style lang="scss" scoped>
.content {
  .settings-list {
    width: 200px;
    background-color: #fff;
    height: 100vh;
    box-sizing: border-box;
    padding-top: var(--status-bar-height);

    .setting-box {
      height: 50px;
      line-height: 50px;
      padding-left: 20px;
      font-size: 15px;
      color: #4f4f4f;
    }
  }
}
</style>
